package vashion.azeroth.api.controller.base;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import vashion.azeroth.back.core.context.BackUserContext;
import vashion.azeroth.core.pojo.BaseObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.List;

public class BaseController {

    @Autowired
    private BackUserContext userContext;

    protected Integer totalCounts; //总记录条数
    protected Integer pageSize;    //每页大小
    protected Integer totalPages;  //总页数
    protected Integer pageNum;     //当前的页

    protected boolean showFirst;   //是否显示首页
    protected boolean showLast;    //是否显示尾页
    protected boolean showNext;    //是否显示下一页
    protected boolean showPrevious;  //是否显示上一页

    protected void initPages(BaseObject object, int totalCounts) {
        this.pageSize = object.getPageSize();
        this.pageNum = object.getPageNum();
        this.totalCounts = totalCounts;
        totalPages = (totalCounts % pageSize == 0) ? totalCounts / pageSize : (totalCounts / pageSize + 1);
        if (totalPages > 0) { //当totalPages <=0时 表明没有任何记录 所有上一页 下一页  首页 末页标签取默认值 不显示
            pageNum = (pageNum <= 0) ? 1 : pageNum;
            pageNum = (pageNum > totalPages) ? totalPages : pageNum;
            showFirst = (pageNum == 1) ? false : true;
            showLast = (pageNum == totalPages) ? false : true;
            showPrevious = (pageNum == 1) ? false : true;
            showNext = (pageNum == totalPages) ? false : true;
            object.setFirstRow(pageSize * (pageNum - 1));
        } else {
            pageNum = 0;
        }
    }

    public Integer getTotalCounts() {
        return totalCounts;
    }

    public void setTotalCounts(Integer totalCounts) {
        this.totalCounts = totalCounts;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public Integer getTotalPages() {
        return totalPages;
    }

    public void setTotalPages(Integer totalPages) {
        this.totalPages = totalPages;
    }

    public Integer getPageNum() {
        return pageNum;
    }

    public void setPageNum(Integer pageNum) {
        this.pageNum = pageNum;
    }

    public boolean isShowFirst() {
        return showFirst;
    }

    public void setShowFirst(boolean showFirst) {
        this.showFirst = showFirst;
    }

    public boolean isShowLast() {
        return showLast;
    }

    public void setShowLast(boolean showLast) {
        this.showLast = showLast;
    }

    public boolean isShowNext() {
        return showNext;
    }

    public void setShowNext(boolean showNext) {
        this.showNext = showNext;
    }

    public boolean isShowPrevious() {
        return showPrevious;
    }

    public void setShowPrevious(boolean showPrevious) {
        this.showPrevious = showPrevious;
    }

    /**
     * 解析上传的excel数据
     *
     * @return
     */
    public List<LinkedHashMap<String, String>> getExcelData(MultipartFile file) throws Exception {

        InputStream inputStream = file.getInputStream();
        Workbook workbook = Workbook.getWorkbook(inputStream);
        Sheet sheet = workbook.getSheet(0);
        List<String> keyList = Lists.newArrayList();
        Cell[] headArr = sheet.getRow(0);
        for (Cell cell : headArr) {
            if (!StringUtils.isBlank(cell.getContents())) {
                keyList.add(cell.getContents());
            }
        }
        List<LinkedHashMap<String, String>> resultList = Lists.newArrayList();

        int rows = sheet.getRows();
        for (int i = 1; i < rows; i++) {
            //mac下 number转excel有个bug，会生成很多空行,这里做下兼容
            LinkedHashMap<String, String> map = Maps.newLinkedHashMap();
            Cell[] cellArr = sheet.getRow(i);
            boolean isAllEmpty = true;
            for (int j = 0; j < cellArr.length; j++) {
                String value = cellArr[j].getContents();
                if (!StringUtils.isBlank(value)) {
                    map.put(keyList.get(j), value);
                    isAllEmpty = false;
                }
            }
            if (!isAllEmpty) {
                resultList.add(map);
            }
        }
        return resultList;
    }

    /**
     * 将数据渲染成excel输出
     *
     * @param title
     * @param response
     */
    public void renderExcel(String title, List<String> keyMapList, HttpServletResponse response)
            throws Exception {

        try {
            response.setContentType("application/dowload");
            response.setHeader(
                    "Content-disposition",
                    "attachment;filename=\""
                            + new String((java.net.URLEncoder.encode(title + ".xls", "UTF-8"))
                            .getBytes("UTF-8"), "GB2312") + "\"");

            HSSFWorkbook workBook = new HSSFWorkbook();
            //在excel中创建一个sheet,在sheet中创建一行,参数为行号(即当前创建的是第二行(这是因为,无论行列,还是表格,在POI中都是从0开始))
            HSSFSheet sheet = workBook.createSheet(title);//表格
            workBook.createSheet();
            workBook.setSheetName(0, title);
            HSSFRow row = sheet.createRow(0);
            HSSFCellStyle cellStyle = workBook.createCellStyle();
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//居中对齐
            //创建HSSFCellStyle实例，并设置上边框、下边框的样式
            cellStyle.setBorderTop((short) 1); // 双线
            cellStyle.setBorderBottom((short) 1); // 单线
            cellStyle.setBorderLeft((short) 1);
            cellStyle.setBorderRight((short) 1);

            //创建HSSFFont实例，设置字体、字号、加粗、颜色
            HSSFFont font = workBook.createFont();
            font.setFontName(HSSFFont.FONT_ARIAL);//字体
            font.setFontHeightInPoints((short) 12);//字号
            font.setColor(HSSFColor.BLACK.index);//颜色
            cellStyle.setFont(font);

            cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            cellStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);

            //构建元数据
            row.setHeightInPoints(20);
            int cellIndex = 0;
            HSSFCell cell;
            for (String entry : keyMapList) {
                sheet.setColumnWidth(cellIndex, entry.getBytes().length * 256);
                cell = row.createCell(cellIndex++);
                cell.setCellValue(entry);
                cell.setCellStyle(cellStyle);
            }
            workBook.write(response.getOutputStream());
            response.getOutputStream().flush();
            response.getOutputStream().close();

        } catch (Exception e) {
            throw e;
        }

    }

    public Long getLoginUserId(HttpServletRequest request) {
        return userContext.getLoginUser(request).getMemberId();
    }

}
